package com.example.outofschool;

import android.util.Log;

import androidx.annotation.NonNull;
import androidx.lifecycle.MutableLiveData;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class MyRepository {
    private final MutableLiveData<String> liveNumber;
    private static final MediaType JSON = MediaType.Companion.get("application/json; charset=utf-8");
    private static final String URL = "https://2a88f0b391b942fe8a79bd79aabbc5af.apig.cn-south-1.huaweicloudapis.com/cqupt/crxNumber";

    public MyRepository(MutableLiveData<String> liveNumber) {
        this.liveNumber = liveNumber;
    }

    public void getNumber(String type, String location) {
        final String[] number = new String[1];
        OkHttpClient okHttpClient = new OkHttpClient();


        JSONObject json = new JSONObject();
        try {
            json.putOpt("type", type);
            json.putOpt("location", location);
        } catch (JSONException e) {
            e.printStackTrace();
        }

        RequestBody requestBody = RequestBody.Companion.create(json.toString(), JSON);
        final Request request = new Request.Builder()
                .url(URL)
                .post(requestBody)
                .build();
        Call call = okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NonNull Call call, @NonNull IOException e) {
                Log.d("myTAG", "onFailure: " + e);
            }

            @Override
            public void onResponse(@NonNull Call call, @NonNull Response response) throws IOException {
                number[0] = Objects.requireNonNull(response.body()).string();
                liveNumber.postValue(number[0]);
//                Log.d("myTAG", number[0]);
            }
        });
    }

    public void connectCloud() {
        final Request request = new Request.Builder()
                .url(URL).head().build();
    }
}
